package fakes

import (
	"context"

	"go-caipu/pkg/plugins"
	"go-caipu/pkg/plugins/backendplugin"
	"go-caipu/pkg/plugins/log"
)

type FakeProcessManager struct {
	StartFunc func(_ context.Context, pluginID string) error
	StopFunc  func(_ context.Context, pluginID string) error
	Started   map[string]int
	Stopped   map[string]int
}

func NewFakeProcessManager() *FakeProcessManager {
	return &FakeProcessManager{
		Started: make(map[string]int),
		Stopped: make(map[string]int),
	}
}

func (m *FakeProcessManager) Start(ctx context.Context, pluginID string) error {
	m.Started[pluginID]++
	if m.StartFunc != nil {
		return m.StartFunc(ctx, pluginID)
	}
	return nil
}

func (m *FakeProcessManager) Stop(ctx context.Context, pluginID string) error {
	m.Stopped[pluginID]++
	if m.StopFunc != nil {
		return m.StopFunc(ctx, pluginID)
	}
	return nil
}

type FakeBackendProcessProvider struct {
	Requested          map[string]int
	Invoked            map[string]int
	BackendFactoryFunc func(context.Context, *plugins.Plugin) backendplugin.PluginFactoryFunc
}

func NewFakeBackendProcessProvider() *FakeBackendProcessProvider {
	f := &FakeBackendProcessProvider{
		Requested: make(map[string]int),
		Invoked:   make(map[string]int),
	}
	f.BackendFactoryFunc = func(ctx context.Context, p *plugins.Plugin) backendplugin.PluginFactoryFunc {
		f.Requested[p.ID]++
		return func(pluginID string, _ log.Logger, _ []string) (backendplugin.Plugin, error) {
			f.Invoked[pluginID]++
			return &FakePluginClient{}, nil
		}
	}
	return f
}

func (pr *FakeBackendProcessProvider) BackendFactory(ctx context.Context, p *plugins.Plugin) backendplugin.PluginFactoryFunc {
	return pr.BackendFactoryFunc(ctx, p)
}
